package gam.t1.appraisal2.dinv.tool;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import pers.neige.neigeitems.item.ItemInfo;
import pers.neige.neigeitems.utils.ItemUtils;

import java.util.List;
import java.util.Map;

public final class RecordSheet {
    private final Map<ItemStack,Record> records = Maps.newLinkedHashMap();
    public void record(ItemStack stack,int total,int init,int index){
        boolean t = false;
        ItemInfo niItem = ItemUtils.isNiItem(stack);
        for (ItemStack _item : records.keySet()) {
            ItemInfo niItem1 = ItemUtils.isNiItem(_item);
            if (niItem1.getId().equals(niItem.getId())){
                Record var = records.get(_item);
                if (!var.a()){
                    var.iB(init);
                    var.add(index);
                }
                t = true;
                break;
            }
        }
        if (!t) records.put(stack, new Record(total,init,index));
    }
    public boolean settlement(Player player){
        if (records.size() > 0){
            if (records.values().stream().allMatch(Record::a)){
                for (ItemStack item : records.keySet()) {
                    Record record = records.get(item);
                    List<Integer> indices = record.indices();
                    for (Integer index : indices) {
                        player.getInventory().setItem(index,null);
                    }
                    if (record.c() > 0){
                        ItemStack clone = item.clone();
                        clone.setAmount(record.c());
                        player.getInventory().addItem(clone);
                    }
                }
                return true;
            }
        }
        return false;
    }
    static class Record {
        private final int a;
        private int b;
        private final List<Integer> indices;

    public Record(int a, int b,int index) {
        this.a = a;
        this.b = b;
        this.indices = Lists.newArrayList(index);
    }
    public boolean a() {
        return b >= a;
    }
    public int b() {
        return b;
    }
    public int c(){
        return b - a;
    }
    public void iB(int m) {
        b+=m;
    }
    public List<Integer> indices() {
        return indices;
    }
    public void add(int index) {
        indices.add(index);
    }
}
}
